package com.stars.easyms.datasource;

import com.stars.easyms.base.trace.EasyMsTraceBean;
import lombok.Getter;
import org.apache.ibatis.mapping.BoundSql;

import java.sql.SQLException;

/**
 * <p>className: SqlExecuteContent</p>
 * <p>description: Sql执行上下文</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019-05-17 16:12
 */
@Getter
public final class SqlExecuteContent extends EasyMsTraceBean {

    private long seq;

    private String sqlId;

    private BoundSql boundSql;

    private volatile long startTime;

    private volatile long endTime;

    private volatile long usedTime = -1;

    private SQLException sqlException;

    SqlExecuteContent(long seq, String sqlId, BoundSql boundSql) {
        this.seq = seq;
        this.sqlId = sqlId;
        this.boundSql = boundSql;
    }

    void setSqlId(String sqlId) {
        this.sqlId = sqlId;
    }

    void setBoundSql(BoundSql boundSql) {
        this.boundSql = boundSql;
    }

    void setSqlException(SQLException sqlException) {
        this.sqlException = sqlException;
    }

    void executeStart() {
        this.startTime = System.currentTimeMillis();
    }

    public long getUsedTime() {
        if (this.startTime == 0) {
            return 0;
        }
        if (this.usedTime >= 0) {
            return this.usedTime;
        }
        if (this.endTime != 0) {
            this.usedTime = this.endTime - this.startTime;
            return this.usedTime;
        }
        return System.currentTimeMillis() - this.startTime;
    }

    void executeEnd() {
        this.endTime = System.currentTimeMillis();
    }
}